package com.gitee.gen.controller;

import com.gitee.gen.common.Action;
import com.gitee.gen.common.GeneratorParam;
import com.gitee.gen.common.Result;
import com.gitee.gen.entity.DatasourceConfig;
import com.gitee.gen.gen.CodeFile;
import com.gitee.gen.gen.GeneratorConfig;
import com.gitee.gen.service.DatasourceConfigService;
import com.gitee.gen.service.GeneratorService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.StringJoiner;

/**
 * @author tanghc
 */
@RestController
@RequestMapping("generate")
public class GeneratorController {

    @Autowired
    private DatasourceConfigService datasourceConfigService;

    @Autowired
    private GeneratorService generatorService;

    @Value("${enable.gen.native:0}")
    private Integer enableGenNative;
    @Value("${gen.workspace:}")
    private String genWorkspace;
    @Value("${gen.workspace.mapperXml.path:}")
    private String genMapperXmlWorkspace;
    @Value("${gen.workspace.entity.path:}")
    private String genEntityWorkspace;
    @Value("${gen.workspace.bo.path:}")
    private String genBoWorkspace;
    @Value("${gen.workspace.query.path:}")
    private String genQueryWorkspace;

    @Value("${gen.workspace.page-query.path:}")
    private String genPageQueryWorkspace;
    @Value("${gen.workspace.volist.path:}")
    private String genVoListWorkspace;
    @Value("${gen.workspace.dto.path:}")
    private String genDtoWorkspace;
    @Value("${gen.workspace.dao.path:}")
    private String genDaoWorkspace;
    @Value("${gen.workspace.service.path:}")
    private String genServiceWorkspace;
    @Value("${gen.workspace.serviceImpl.path:}")
    private String genServiceImplWorkspace;
    @Value("${gen.workspace.controller.path:}")
    private String genControllerWorkspace;
    @Value("${gen.workspace.biz.domain:}")
    private String genBizDomainWorkspace;

    /**
     * 生成代码
     *
     * @param generatorParam 生成参数
     * @return 返回代码内容
     */
    @RequestMapping("/code")
    public Result code(@RequestBody GeneratorParam generatorParam) {
        int datasourceConfigId = generatorParam.getDatasourceConfigId();
        DatasourceConfig datasourceConfig = datasourceConfigService.getById(datasourceConfigId);
        GeneratorConfig generatorConfig = GeneratorConfig.build(datasourceConfig);
        List<CodeFile> generate = generatorService.generate(generatorParam, generatorConfig);

        if (StringUtils.isNotBlank(genWorkspace) && enableGenNative == 1) {
            for (CodeFile codeFile : generate) {
                String content = codeFile.getContent();
                if (StringUtils.isBlank(content)) {
                    continue;
                }
                String packagePath = StringUtils.EMPTY;
                if ("Entity".equalsIgnoreCase(codeFile.getFolder()) || "model".equalsIgnoreCase(codeFile.getFolder())|| "DO".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genEntityWorkspace;
                } else if ("BO".equalsIgnoreCase(codeFile.getFolder()) || "VO".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genBoWorkspace;
                } else if ("DTO".equalsIgnoreCase(codeFile.getFolder()) || "Container".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genDtoWorkspace;
                } else if ("DAO".equalsIgnoreCase(codeFile.getFolder()) || "MAPPER".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genDaoWorkspace;
                } else if ("service".equalsIgnoreCase(codeFile.getFolder()) || "ServiceImpl".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genServiceWorkspace;
                } else if ("controller".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genControllerWorkspace;
                }else if ("Query".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genQueryWorkspace;
                }else if ("PageQuery".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genPageQueryWorkspace;
                }else if ("ListVO".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genVoListWorkspace;
                }else if ("vl-ServiceImpl".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genServiceImplWorkspace;
                }else if ("mapper.xml".equalsIgnoreCase(codeFile.getFolder())) {
                    packagePath = genMapperXmlWorkspace;
                }
                if (StringUtils.isNotBlank(genBizDomainWorkspace)) {
                    content = content.replace("${bizDomain}", genBizDomainWorkspace);
                }

                if (StringUtils.isEmpty(packagePath)) {
                    System.out.println("packagePath 为空");
                    continue;
                }
                StringBuilder stringBuilder = new StringBuilder(genWorkspace);
                stringBuilder.append(File.separator)
                        .append(packagePath)
                        .append(File.separator)
                        .append(codeFile.getFileName());
                File file = new File(stringBuilder.toString());
                if (file.exists()) {
                    file.delete();
                }
                try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
                    FileCopyUtils.copy(content.getBytes(StandardCharsets.UTF_8), fileOutputStream);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return Action.ok(generate);
    }

}
